<!-- src/views/outbound/outboundorder/index.vue -->
<script setup>
import { onMounted, ref, computed } from 'vue'
import dial from './dial.vue'
import WarehouseDial from './WarehouseDial.vue'
import { getAllApi, updateByIdApi } from '@/api/outbound/outboundorder'
import { getItemsApi, updateApi } from '@/api/outbound/outboundorderdetails'
import { getSkuInfoApi } from '@/api/item'
import display from './display.vue' // 引入新组件
// import { getInfoApi } from '@/api/customer/customer'
import { ElMessage } from 'element-plus'

const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)
const size = ref('default')
const background = ref(true)
const disabled = ref(false)
const customerList = ref([])


const mockCustomerList = [
  { id: 1001, name: '客户A' },
  { id: 1002, name: '客户B' },
  { id: 1003, name: '客户C' },
  { id: 1004, name: '客户D' }
]
// 计算客户名称
const customerName = computed(() => {
  const customer = customerList.value.find(item => item.id === dialogFormData.value.customerId)
  return customer ? customer.name : ''
})
// 获取客户列表
const getCustomerList = async () => {
  // const res = await getInfoApi()
  // customerList.value = res.map(item => ({ label: item.name, value: item.id }))
}

const itemsList = ref()
//获取商品列表
const getItemsList = async () => {
  let res = await getSkuInfoApi()
  itemsList.value = res.data || res
}
const outboundorderdetailsId = ref(null)
const outboundorderId = ref(null)

const items = ref()
const selectedGoodsList = ref([])
const handleConfirm = async (id) => {
  try {
    // 确保商品列表已加载
    if (!itemsList.value || itemsList.value.length === 0) {
      await getItemsList()
    }
    outboundorderId.value = id
    // 获取出库单明细数据
    let res = await getItemsApi(id)
    items.value = res.data || res

    // 根据 skuId 关联商品信息和出库明细
    selectedGoodsList.value = items.value.map(item => {
      outboundorderdetailsId.value = item.id
      // 在商品列表中查找对应的 sku 信息
      const skuInfo = itemsList.value.find(sku => sku.id === item.skuId)

      // 提供默认值以防找不到匹配的商品信息
      return {
        id: item.skuId || item.id || 0,
        name: skuInfo ? skuInfo.title : (item.skuName || `商品-${item.skuId}`),
        code: skuInfo ? skuInfo.code : (item.skuCode || ''),
        specCode: skuInfo ? skuInfo.commodityCode : (item.specCode || ''),
        totalQuantity: item.outCount || item.quantity || 0
      }
    })
    console.log('最终的商品列表数据:', selectedGoodsList.value)
    warediaRef.value.open()
  } catch (error) {
    console.error('处理出库单明细失败:', error)
    ElMessage.error('处理出库单明细失败!')
  }
}
// 处理从商品选择弹窗获取的数据
const onItemConfirm = (items) => {
  // 将选择的商品转换为WarehouseDial需要的格式
  selectedGoodsList.value = items.map(item => ({
    id: item.id,
    name: item.title,
    code: item.code,
    specCode: item.commodityCode,
    totalQuantity: 0 // 这个值可能需要从其他地方获取
  }))
  // 打开仓库选择弹窗
  warediaRef.value.open()
}

// 处理仓库信息提交
const handleWarehouseSubmit = async (data) => {
  console.log('仓库信息提交:', warediaRef.value.warehouseList)
  // 在这里处理提交的仓库分配信息
  const request = {
    id: outboundorderdetailsId.value,
    targetWarehouseId: data.warehouseStock.warehouseId,
    targetWarehouseAreaId: data.warehouseStock.areaId,
    targetWarehouseAreaLocaId: data.warehouseStock.locationId
  }
  let res = await updateApi(request)
  let rres = await updateByIdApi(outboundorderId.value)
  if (res.code && rres.code) {
    ElMessage.success('操作成功！')
  } else {
    ElMessage.error('操作失败!')
  }
}
// 状态映射
const statusMap = {
  1: '预发货',
  2: '确认发货',
  3: '拣货中',
  4: '拣货完成',
  5: '待打包',
  6: '待称重',
  7: '待发货',
  8: '已发货',
  9: '已签收'
}

// 搜索表单
const form = ref({
  invoiceCode: '',
  status: '',
  customerId: ''
})
// 获取数据
const getAll = async () => {
  const res = await getAllApi(form.value.invoiceCode, form.value.customerId, form.value.status, currentPage.value, pageSize.value)
  total.value = res.total
  tableData.value = res.rows
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getAll()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getAll()
}



const search = () => {
  currentPage.value = 1
  getAll()
}

const ids = ref(null)
const handleSelectionChange = (val) => {
  ids.value = val.map(item => item.id)
}


// 弹窗引用
const diaRef = ref(null)
const warediaRef = ref(null)
const handleAdd = () => {
  diaRef.value.dialogVisible = true
}
const displayRef = ref(null)

const handleDis = async (row) => {
  try {
    if (!itemsList.value || itemsList.value.length === 0) {
      await getItemsList()
    }

    let res = await getItemsApi(row.id)
    const items = res.data || res

    selectedGoodsList.value = items.map(item => {
      const skuInfo = itemsList.value.find(sku => sku.id === item.skuId)
      return {
        id: item.skuId || item.id || 0,
        code: skuInfo ? skuInfo.code : (item.skuCode || ''),
        name: skuInfo ? skuInfo.title : (item.skuName || `商品-${item.skuId}`),
        description: skuInfo ? skuInfo.description : '',
        specCode: skuInfo ? skuInfo.commodityCode : (item.specCode || ''),
        specName: skuInfo ? skuInfo.specName : (item.specName || ''),
        unit: skuInfo ? skuInfo.unit : '',
        totalQuantity: item.outCount || item.quantity || 0
      }
    })

    displayRef.value.open() // 打开明细弹窗
  } catch (error) {
    ElMessage.error('获取商品明细失败！')
  }
}

defineExpose({
  refreshData: getAll
})

onMounted(() => {
  getAll()
  getCustomerList()
  getItemsList()
})
</script>

<template>
  <dial ref="diaRef" @refresh="getAll" :customer-list="mockCustomerList" />
  <display ref="displayRef" :items="selectedGoodsList" />
  <WarehouseDial ref="warediaRef" :goods-list="selectedGoodsList" @submit="handleWarehouseSubmit" />
  <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
    <el-button @click="handleAdd" type="primary">新增</el-button>
  </div>

  <el-form :model="form" :inline="true" style="margin-bottom: 20px;">
    <el-form-item label="发货单号">
      <el-input v-model="form.invoiceCode" placeholder="请输入发货单号" />
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="form.status" placeholder="请选择状态" style="width: 120px;">
        <el-option v-for="(label, key) in statusMap" :key="key" :label="label" :value="key" />
      </el-select>
    </el-form-item>
    <el-form-item label="客户名称">
      <el-input v-model="form.invoiceCode" placeholder="请输入客户名称" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="invoiceCode" label="发货单号" />
    <el-table-column prop="status" label="发货单状态">
      <template #default="{ row }">{{ statusMap[row.status] }}</template>
    </el-table-column>
    <el-table-column prop="totalCount" label="总数量" />
    <el-table-column prop="totalWeight" label="总重量" />
    <el-table-column prop="totalVolume" label="总体积" />
    <el-table-column prop="customerName" label="客户名称" />
    <el-table-column prop="createBy" label="创建人" />
    <el-table-column fixed="right" label="操作" width="300">
      <template #default="{ row }">
        <el-button size="small" @click="handleDis(row)">查看</el-button>
        <el-button size="small" @click="handleConfirm(row.id)">确认</el-button>
        <el-button size="small" @click="">拣货复核</el-button>
        <el-button size="small" type="danger" @click="delById(row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
      :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>